package dao.user;

import common.JdbcUtils;
import domain.user.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 文件描述
 * 针对数据库的实现
 *
 * @Author 冯根源
 * @create 2020/4/2 11:02
 */
public class JDBCUserDaoImpl implements UserDao {

    @Override
    public void add(User form) {
        Connection connection = null;
        PreparedStatement stm = null;

        try {
            //得到连接
            connection = JdbcUtils.getConnection();
            //准备模板
            String sql = "INSERT INTO t_user VALUES(?,?,?,?)";
            stm = connection.prepareStatement(sql);
            //为stm赋值
            stm.setString(1, form.getUsername());
            stm.setString(2, form.getPassword());
            stm.setInt(3, form.getAge());
            stm.setString(4, form.getSex());
            stm.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection, stm);
        }
    }

    @Override
    public User FindByUserName(String username) {
        Connection connection = null;
        PreparedStatement stm = null;
        ResultSet resultSet = null;

        try {
            //得到连接
            connection = JdbcUtils.getConnection();
            //准备模板
            String sql = "SELECT * FROM t_user WHERE  username=?";
            stm = connection.prepareStatement(sql);
            //为stm赋值
            stm.setString(1, username);
            //得到ResultSet表
            resultSet = stm.executeQuery();
            //把resultSet转换成User对象
            if (resultSet == null) {
                return null;
            }
            if(resultSet.next()){
                //吧resultset转换成user对象
                //ORM --> 对象关系映射
                User user = new User();
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setAge(resultSet.getInt("age"));
                user.setSex(resultSet.getString("sex"));

                return user;
            }else{
                return null;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection, stm, resultSet);
        }

        return null;
    }
}
